package net.m510.autosurfer.nifty;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.logging.Logger;

import net.m510.autosurfer.common.DocumentPostProcess;
import net.m510.autosurfer.core.DocumentResponseHandler;
import net.m510.autosurfer.core.Parameters;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.FormElement;

public class NiftyLogin extends DocumentPostProcess {
	private static final Logger log = Logger.getLogger(NiftyLogin.class.getName());

	private String userId;
	private String password;

	public NiftyLogin() {
		this(null,null);
	}
	public NiftyLogin(CloseableHttpClient client, HttpClientContext context) {
		super(client, context);
		super.log = log;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	protected List<NameValuePair> getRequestParameters(Document doc) {
		FormElement form = doc.getAllElements().forms().get(0);
		Parameters p = Parameters.create(form);
		p.put("username", this.userId);
		p.put("password", this.password);
		return p.asNameValueList();
	}
	@Override
	protected URI getUri(Document doc) {
		String action = doc.getAllElements().forms().get(0).attr("action");
		HttpHost host = context.getTargetHost();
		URI uri;
		try {
			uri = URIUtils.resolve(URI.create(host.toURI()), host,context.getRedirectLocations());
			log.fine("first uri = "+uri);
			uri = uri.resolve(action);
			log.fine("resolved uri = "+uri);
		} catch (URISyntaxException e) {
			throw new IllegalStateException("cannot resolve uri",e);
		}
		return uri;
	}
	public String getActualCharset() {
		return ((DocumentResponseHandler)getResponseHandler()).getActualCharset();
	}
}